package com.md.config.database;

import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.actuate.autoconfigure.jdbc.DataSourceHealthContributorAutoConfiguration;
import org.springframework.boot.actuate.health.AbstractHealthIndicator;
import org.springframework.boot.actuate.jdbc.DataSourceHealthIndicator;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.jdbc.metadata.DataSourcePoolMetadataProvider;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;

import javax.sql.DataSource;
import java.util.Map;

/**
 * 2021-09-25 1:16
 *
 * @author 刘骄阳
 */
@Configuration
@ConditionalOnClass(value = {MybatisPlusInterceptor.class})
@Slf4j
public class MyDataSourceHealthConfig extends DataSourceHealthContributorAutoConfiguration {
  @Autowired
  public MyDataSourceHealthConfig(final Map<String, DataSource> dataSources,
                                  final ObjectProvider<DataSourcePoolMetadataProvider> metadataProviders) {
    super(dataSources, metadataProviders);
    dataSources.forEach((key, value) -> log.info("{}---{}", key, value));
  }

  /**
   * 自定义健康检查
   *
   * @param source 数据源
   * @return indicator
   */
  @Override
  protected AbstractHealthIndicator createIndicator(final DataSource source) {
    AbstractHealthIndicator indicator = super.createIndicator(source);
    if (indicator instanceof DataSourceHealthIndicator) {
      DataSourceHealthIndicator dataSourceHealthIndicator = (DataSourceHealthIndicator) indicator;
      if (!StringUtils.hasText(dataSourceHealthIndicator.getQuery())) {
        dataSourceHealthIndicator.setQuery("SELECT 1");
      }
      return dataSourceHealthIndicator;
    } else {
      indicator.health();
    }
    return indicator;
  }
}
